import axios from 'axios'
import { Message } from 'element-ui'
import { Notification } from 'element-ui'
import store from '@/store'
import { getToken, getRefreshToken, setToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: 'http://127.0.0.1:8899', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000000000000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */
  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  async response => {
    const res = response.data
    // 当状态码不等于200，打印错误消息
    // if (response.status !== 200) {
    //   Message({
    //     message: res.msg || '错误',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })
    //   return Promise.reject(new Error(res.msg || '错误'))
    // }
    console.log(res.code)
    // 判断接口权限是否异常
    if (res.code === 4003) {
      Notification({
        title: '错误',
        message: res.msg.join(',') || '错误',
        type: 'error'
      })
      return Promise.reject(new Error(res.msg.join(',') || '错误'))
    }

    // 判断是否是刷新token过期
    if (res.code === 4002) {
      Notification({
        title: '错误',
        message: res.msg.join(',') || '错误',
        type: 'error'
      })
      return Promise.reject(new Error(res.msg.join(',') || '错误'))
    }

    // 判断是否是token过期 如果是token过期，将刷新token设置到请求token，然后发起获取token请求
    if (res.code === 4001) {
      // 将刷新token设置在请求token中
      setToken(getRefreshToken())
      // 根据刷新token获取请求token和刷新token
      await store.dispatch('user/getTokenByRefreshToken').then(resp => {
        return res
      }).catch(() => {
        Notification({
          title: '错误',
          message: res.msg.join(',') || '错误',
          type: 'error'
        })
        return Promise.reject(new Error(res.msg.join(',') || '错误'))
      })
    }

    if (res.code === 1) {
      Notification({
        title: '错误',
        message: res.msg.join(',') || '错误',
        type: 'error'
      })
      return Promise.reject(new Error(res.msg.join(',') || '错误'))
    }
    return res
    // if the custom code is not 20000, it is judged as an error.
    // if (res.code !== 20000) {
    //   Message({
    //     message: res.message || 'Error',
    //     type: 'error',
    //     duration: 5 * 1000
    //   })

    //   // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    //   if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
    //     // to re-login
    //     MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
    //       confirmButtonText: 'Re-Login',
    //       cancelButtonText: 'Cancel',
    //       type: 'warning'
    //     }).then(() => {
    //       store.dispatch('user/resetToken').then(() => {
    //         location.reload()
    //       })
    //     })
    //   }
    //   return Promise.reject(new Error(res.message || 'Error'))
    // } else {
    //   return res
    // }
  },
  error => {
    const errR = error.response
    Message({
      message: errR.data.msg,
      type: 'error',
      duration: 3 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
